package smashedapples.core
{
	import flash.events.Event;
	import flash.utils.getQualifiedClassName;
	
	import mx.events.PropertyChangeEvent;
	
		
	public class Controller extends NonVisualComponent
	{	
		
		public function Controller(view:View=null)
		{
			super();
			if( view != null)
				this.$view = view;	
		}
		
		
		
		public function addListeners( events:Array = null ):void
		{
			if( events == null || this.$view == null )
 				return;
			
			for each( var event:String in events)
			{
				this.$view.addEventListener( event, execute, true );
			}	
		}
		
		
		public function execute(event:Event):void
		{	
			if( event is PropertyChangeEvent)
				 return this.handlePropertyChange( event as PropertyChangeEvent);
	
			var handlerName : String = getExecuteHandlerName( event );

			trace(handlerName +  "(" + flash.utils.getQualifiedClassName(event) + ")");
			if( this.hasOwnProperty(handlerName))
			{
				var method : Function = this[handlerName] as Function;
				method.apply( this, [event] );
			}
		}
		
		protected function getExecuteHandlerName( event:Event ):String
		{
			return "on" + event.type.substr(0,1).toUpperCase() + event.type.slice(1);
		}
		
		
		private function handlePropertyChange(event:PropertyChangeEvent):void
		{	
			var handlerName : String = "on" + event.property.substr(0,1).toUpperCase() + event.property.slice(1) + "Change";
			
			/* trace(handlerName +  "(" + flash.utils.getQualifiedClassName(event) + ")"); */
			
			if( this.hasOwnProperty(handlerName))
			{
				var method : Function = this[handlerName] as Function;
				method.apply( this, [event] );
			}
			
			return;
		}
		
		
		public var $view : View;
		
		
	}
}